package cn.he4966.bingguo;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

@RestController
public class Http {
    @Autowired
    private ObjectMapper objectMapper; // 自动装配ObjectMapper对象

    @RequestMapping("/http_get")
    public String http_get(String url) throws JsonProcessingException {
        Map<String, Object> data = new HashMap<>();
        data.put("code", 1);
        Document doc = null;
        try {
            doc = Jsoup.connect(url)
                    .followRedirects(true).get();// to follow redirects
            String html = doc.body().html();
            data.put("data", html);
        } catch (IOException e) {
            // throw new RuntimeException(e);
            data.put("code", 0);
            data.put("data", e.getMessage());
        }
        return objectMapper.writeValueAsString(data);
    }

    // JSONObject json = new JSONObject(str);

    @RequestMapping("/bingo_get")
    public String bingguo_get(String pageSize, String date, String pageNum) throws JsonProcessingException {
        if (pageSize == null || pageSize.isEmpty())
            pageSize = "1";
        if (pageNum == null || pageNum.isEmpty())
            pageNum = "1";
        if (date == null || date.isEmpty())
            // 获取今天的日期2024-04-28
            date = LocalDate.now().toString();

        System.out.println("pageSize:" + pageSize + "pageNum:" + pageNum + " date:" + date);
        Map<String, Object> data = new HashMap<>();
        data.put("code", 1);
        String html = "";
        String url = "https://xn--kpro5poukl1g.com/taiwanlottery/TLCAPIWeB/Lottery/BingoResult?openDate=" + date
                + "&pageNum=" + pageNum + "&pageSize=" + pageSize;

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful() && response.body() != null) {
                html = response.body().string();
                data.put("data", html);
                // 处理采集到的数据
                // System.out.println(html);
                // 这里可以添加代码将数据存储到数据库或进行其他处理
                // 把 html json 字符串转换为 Map 对象
                try {
                    Map<String, Object> jsonMap = objectMapper.readValue(html, Map.class);
                    if (jsonMap.containsKey("rtCode") && jsonMap.get("rtCode").equals(0)) {

                        System.out.println(jsonMap.keySet());// 获取全部 key
                        if (jsonMap.containsKey("content")) {
                            data.put("data", jsonMap.get("content"));
                        }

                    } else {
                        data.put("code", 0);
                    }

                } catch (Exception e) {
                    data.put("code", 0);
                    data.put("msg", e.getMessage());
                }

            } else {
                System.out.println("请求失败: " + response);
                data.put("code", 0);
            }

        } catch (IOException e) {
            data.put("code", 0);
            data.put("data", e.getMessage());
        }
        return objectMapper.writeValueAsString(data);
    }
}
